<template>
  <div class="register-container">
    <div class="register-box">
      <h2>用户注册</h2>
      <el-form :model="form" :rules="rules" ref="form" class="register-form" label-width="100px">
        <el-form-item label="用户类型" prop="userType">
          <el-radio-group v-model="form.userType">
            <el-radio label="user">普通用户</el-radio>
            <el-radio label="merchant">商家</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" prefix-icon="el-icon-user" placeholder="请输入用户名">
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input v-model="form.password" prefix-icon="el-icon-lock" type="password" placeholder="请输入密码"
            show-password>
          </el-input>
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input v-model="form.confirmPassword" prefix-icon="el-icon-lock" type="password" placeholder="请确认密码"
            show-password>
          </el-input>
        </el-form-item>

        <el-form-item prop="phone">
          <el-input v-model="form.phone" prefix-icon="el-icon-mobile-phone" placeholder="请输入手机号">
          </el-input>
        </el-form-item>

        <el-form-item prop="email">
          <el-input v-model="form.email" prefix-icon="el-icon-message" placeholder="请输入邮箱">
          </el-input>
        </el-form-item>

        <!-- 宠物信息部分，仅对普通用户显示 -->
        <template v-if="form.userType === 'user'">
          <h3>宠物信息</h3>
          <div v-for="(pet, index) in form.pets" :key="index" class="pet-form-section">
            <div class="pet-form-header">
              <h4>宠物 {{ index + 1 }}</h4>
              <el-button v-if="index > 0" type="text" class="delete-pet-btn" @click="removePet(index)">
                删除
              </el-button>
            </div>
            <el-form-item :prop="'pets.' + index + '.name'" :rules="petRules.name">
              <el-input v-model="pet.name" prefix-icon="el-icon-pet" placeholder="请输入宠物名称">
              </el-input>
            </el-form-item>

            <el-form-item :prop="'pets.' + index + '.type'" :rules="petRules.type">
              <el-select v-model="pet.type" placeholder="请选择宠物类型" style="width: 100%">
                <el-option label="狗狗" value="dog"></el-option>
                <el-option label="猫咪" value="cat"></el-option>
                <el-option label="其他" value="other"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item :prop="'pets.' + index + '.breed'" :rules="petRules.breed">
              <el-input v-model="pet.breed" placeholder="请输入宠物品种">
              </el-input>
            </el-form-item>

            <el-form-item :prop="'pets.' + index + '.age'" :rules="petRules.age">
              <div class="age-input-wrapper">
                <el-input-number v-model="pet.age" :min="0" :max="30" placeholder="请输入宠物年龄">
                </el-input-number>
                <span class="age-unit">岁</span>
              </div>
            </el-form-item>
          </div>

          <el-button type="primary" plain @click="addPet" class="add-pet-btn">
            <i class="el-icon-plus"></i> 添加宠物
          </el-button>
        </template>

        <el-form-item>
          <el-button type="primary" class="register-button" @click="handleRegister">注册</el-button>
        </el-form-item>

        <div class="login-link">
          已有账号？<router-link to="/login">立即登录</router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'RegisterPage',
  data() {
    // 密码确认验证
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      form: {
        username: '',
        password: '',
        confirmPassword: '',
        email: '',
        phone: '',
        userType: 'user', // 默认为普通用户
        pets: [
          {
            name: '',
            type: '',
            breed: '',
            age: 0
          }
        ]
      },
      rules: {
        userType: [
          { required: true, message: '请选择用户类型', trigger: 'change' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      },
      petRules: {
        name: [
          { required: true, message: '请输入宠物名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择宠物类型', trigger: 'change' }
        ],
        breed: [
          { required: true, message: '请输入宠物品种', trigger: 'blur' }
        ],
        age: [
          { required: true, message: '请输入宠物年龄', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    'form.userType': {
      handler(newType) {
        // 当切换到商家注册时，清空宠物信息
        if (newType === 'merchant') {
          this.form.pets = []
        } else if (newType === 'user' && this.form.pets.length === 0) {
          // 当切换回普通用户时，添加一个空的宠物信息
          this.form.pets = [{
            name: '',
            type: '',
            breed: '',
            age: 0
          }]
        }
      },
      immediate: true
    }
  },
  methods: {
    addPet() {
      this.form.pets.push({
        name: '',
        type: '',
        breed: '',
        age: 0
      });
    },
    removePet(index) {
      this.form.pets.splice(index, 1);
    },
    handleRegister() {
      const { username, password, userType, phone, email } = this.form;
      const users = JSON.parse(localStorage.getItem('users') || '[]');
      const merchants = JSON.parse(localStorage.getItem('merchants') || '[]');

      // 检查用户名是否已存在
      const allUsers = [...users, ...merchants];
      if (allUsers.some(user => user.username === username)) {
        this.$message.error('用户名已存在');
        return;
      }

      // 根据用户类型存储数据
      const newUser = { username, password, userType, phone, email };
      if (userType === 'user') {
        newUser.pets = this.form.pets; // 添加宠物信息
        users.push(newUser);
        localStorage.setItem('users', JSON.stringify(users));
      } else if (userType === 'merchant') {
        merchants.push(newUser);
        localStorage.setItem('merchants', JSON.stringify(merchants));
      }
      //登录成功
      localStorage.setItem('currentUser', JSON.stringify(user));
      this.$emit('login-success', user);
      this.$router.push('/');

      // 更新全局状态（如 Vuex）
      this.$store.dispatch('login', newUser); // 假设 Vuex 中有 login action

      // 跳转到商家管理页面
      if (userType === 'merchant') {
        this.$router.push('/merchant/dashboard'); // 跳转到商家管理页面
      } else {
        this.$router.push('/'); // 普通用户跳转到首页
      }
    }
  }
}
</script>

<style scoped>
.register-container {
  min-height: calc(100vh - 200px);
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  padding: 40px 0;
}

.register-box {
  width: 500px;
  padding: 40px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.register-box h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.register-box h3 {
  margin: 20px 0;
  color: #666;
  font-size: 16px;
}

.register-form {
  margin-top: 20px;
}

.register-button {
  width: 100%;
  padding: 12px 0;
  margin-top: 20px;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

.login-link a {
  color: #409EFF;
  text-decoration: none;
}

.el-input {
  margin-bottom: 20px;
}

.pet-form-section {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.pet-form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pet-form-header h4 {
  margin: 0;
  color: #333;
}

.delete-pet-btn {
  color: #F56C6C;
}

.add-pet-btn {
  width: 100%;
  margin-bottom: 20px;
}

.age-input-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.age-unit {
  color: #666;
  font-size: 14px;
}

.el-input-number {
  width: 180px;
}
</style>